package com.example.denglu.util;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.profile.DefaultProfile;

import java.util.Random;
import java.util.List;
import java.util.ArrayList;
import java.util.concurrent.atomic.AtomicInteger;

public class SmsUtil {
    // 阿里云短信服务配置列表
    private static final List<SmsConfig> SMS_CONFIGS = new ArrayList<>();
    private static final AtomicInteger currentIndex = new AtomicInteger(0);
    
    static {
        // 添加多个短信服务配置
        SMS_CONFIGS.add(new SmsConfig(
            "LTAI5tQ5F8JJ4zQeoHVw5HK5",
            "2CChkfcyIklYuF6LSjCMeGjJwhtUkL",
            "kl6",
            "SMS_476535134"
        ));
        
        // 添加更多配置
        SMS_CONFIGS.add(new SmsConfig(
            "LTAI5tCWBmC5HdkQgL9qfMdk",
            "hOCltJMsm9xwe5e5SBH6EbJzY28NV4",
            "kl6",
            "SMS_476470193"
        ));
        SMS_CONFIGS.add(new SmsConfig(
            "LTAI5tCgpWKKHYSty18sD3RR",
            "wGOu9NujnQlw0a8MpMLAAO3CGw8kM1",
            "kl6",
            "SMS_476490187"
        ));
        
        // 可以继续添加更多配置...
    }
    
    private static final String REGION_ID = "cn-hangzhou";

    // 获取下一个可用的配置
    private static SmsConfig getNextConfig() {
        int index = currentIndex.getAndIncrement() % SMS_CONFIGS.size();
        return SMS_CONFIGS.get(index);
    }

    /**
     * 发送短信验证码
     * @param phoneNumbers 手机号码
     * @param code 验证码
     * @return 是否发送成功
     * @throws RuntimeException 当发送失败时抛出异常
     */
    public static boolean sendSms(String phoneNumbers, String code) {
        System.out.println("开始发送短信");
        System.out.println("手机号：" + phoneNumbers);
        System.out.println("验证码：" + code);

        // 遍历所有配置尝试发送
        RuntimeException lastException = null;
        
        for (int i = 0; i < SMS_CONFIGS.size(); i++) {
            try {
                SmsConfig config = getNextConfig();
                System.out.println("尝试使用配置 " + (i + 1));
                
                // 初始化 Client
                DefaultProfile profile = DefaultProfile.getProfile(
                        REGION_ID, config.getAccessKeyId(), config.getAccessKeySecret());
                IAcsClient client = new DefaultAcsClient(profile);

                // 组装请求对象
                SendSmsRequest request = new SendSmsRequest();
                request.setPhoneNumbers(phoneNumbers);
                request.setSignName(config.getSignName());
                request.setTemplateCode(config.getTemplateCode());
                request.setTemplateParam("{\"code\":\"" + code + "\"}");

                // 发送请求
                SendSmsResponse response = client.getAcsResponse(request);
                System.out.println("短信API响应 - Code: " + response.getCode() + 
                                 ", Message: " + response.getMessage() + 
                                 ", BizId: " + response.getBizId());

                // 处理业务限制
                if ("isv.BUSINESS_LIMIT_CONTROL".equals(response.getCode())) {
                    System.out.println("当前配置触发业务限制，尝试下一个配置");
                    lastException = new RuntimeException("短信发送频率超限");
                    continue;
                }

                // 处理其他错误
                if ("OK".equals(response.getCode())) {
                    return true;
                }
                
                System.out.println("当前配置发送失败，尝试下一个配置");
                
            } catch (Exception e) {
                System.out.println("当前配置发送异常：" + e.getMessage());
                lastException = new RuntimeException(e.getMessage());
            }
        }

        // 所有配置都尝试失败
        if (lastException != null) {
            throw lastException;
        }
        return false;
    }

    /**
     * 生成6位随机验证码
     */
    public static String generateCode() {
        return String.format("%06d", new Random().nextInt(1000000));
    }

    /**
     * 验证手机号格式
     * @param phoneNumber 手机号码
     * @return 是否是有效的手机号
     */
    public static boolean isValidPhoneNumber(String phoneNumber) {
        return phoneNumber != null && phoneNumber.matches("^1[3-9]\\d{9}$");
    }
    
    // 短信配置类
    private static class SmsConfig {
        private final String accessKeyId;
        private final String accessKeySecret;
        private final String signName;
        private final String templateCode;
        
        public SmsConfig(String accessKeyId, String accessKeySecret, 
                        String signName, String templateCode) {
            this.accessKeyId = accessKeyId;
            this.accessKeySecret = accessKeySecret;
            this.signName = signName;
            this.templateCode = templateCode;
        }
        
        public String getAccessKeyId() { return accessKeyId; }
        public String getAccessKeySecret() { return accessKeySecret; }
        public String getSignName() { return signName; }
        public String getTemplateCode() { return templateCode; }
    }
} 